package com.pearadmin.pro.common.security.handler;

import com.alibaba.fastjson.JSON;
import com.pearadmin.pro.common.tools.web.ServletUtil;
import com.pearadmin.pro.common.web.domain.Result;
import com.pearadmin.pro.common.web.domain.ResultCode;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Describe: 自定义 Security 登陆失败处理类
 * Author: 就 眠 仪 式
 * CreateTime: 2019/10/23
 * */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * Describe: 自定义 Security 登陆失败处理结果
     * Author: 就 眠 仪 式
     * CreateTime: 2019/10/23
     * */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        Result result = Result.failure(ResultCode.LOGIN_FAILURE.getCode(), ResultCode.LOGIN_FAILURE.getMessage());

        if(e instanceof UsernameNotFoundException){
            result.setMsg("用户名不存在");
        }
        if(e instanceof LockedException){
            result.setMsg("用户冻结");
        }
        if(e instanceof BadCredentialsException){
            result.setMsg("账户密码不正确");
        }

        ServletUtil.write(JSON.toJSONString(result));
    }
}
